// pages/classdetails/classdetails.js
import { Classdetails } from '../../model/classdetails.js'
const classdetails = new Classdetails();
var WxParse = require('../../wxParse/wxParse.js');
// var util = require("../../utils/util.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //视频是否播放
    isvideo:false,
    // tab
    categoryMenu: ["简介", "课程"],
    categoryCur: 0,
    id:'',
    classobj:{},
    Url:'',
    video:{},
    num:'',
    content:'',
    detailList:[],
    detailListCount:0,
    obj:{
      time:'',
      sss:''
    },
    page:0,
    videourl:'',
    timeStamp:'',
    timeStampresult:'20000',
    playLength:0,
    totalLength:0,
    progress:false,
    again:true,
    totaltime:0,
    isplay:false,
    videoId:'',
    videosId:'',
    detailsId:'',
    timeNumber:0,
    autoplay:false,
    historySeconds:0,
    surplusTime:0,
    shitime:0,
    isUpTime:false
    // playshop:true,//播放按钮
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log("onReady");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // console.log("onshow");
    
  },
   /**
   * 生命周期函数--监听页面加载
   */
  


  onLoad: function (options) {
    console.log("onLoad");
    var that=this
    
    that.init_video_time(options.videoId);

    // that.setData({
    //   historySeconds:200
    // })
    // var videoContext = wx.createVideoContext('myVideo');
    // that.setData({
    //   autoplay:true
    // })
    // videoContext.seek(120);
    
    

    // that.setData({
    //   playLength:100,
    //   timeNumber:200
    // })
    console.log(options)
    that.setData({
      id:options.id,
      videoId:options.videoId,
      // detailList:[]

    })


    that.classdetail()
    // that.video()
    that.viewoList();
    
    
  },
    init_video_time(videoId){

      //console.log("source:"+source);

      var that = this;
      var historyTime = 0;
      historyTime = wx.getStorageSync(videoId);
      if(historyTime == ''){
        historyTime=0;
      }
      // console.log("AAAAA");
      // console.log(historyTime);
      // if(source ==1){
      //   that.setData({
      //     isplay:true
      //   })
      // }
      
      let videoContext = wx.createVideoContext("myvideo");
      if(videoContext){
        videoContext.stop() //停止播放视频
      }
      if(videoContext){
        that.setData({
          historySeconds:historyTime
        })
        setTimeout(()=>{  //300毫秒延迟
          videoContext.play() //开始播放视频
          // that.setData({
          //   isplay:true
          // })
          // console.log('aaa')
        },500)
      }
    },
  
    //播放时长
    timeupdate(e){
     if(this.data.progress){
      return false;
     }
     //此处判断是否已经播放了70%
     var currentTime = Number(e.detail.currentTime).toFixed(0);
     var durationTime = Number(e.detail.duration).toFixed(0);
     if(!this.data.isUpTime){
      console.log();
      
      var percent = ((currentTime/durationTime)*100).toFixed(0);
      console.log("currentTime:"+currentTime);
      console.log("durationTime:"+durationTime);
      console.log("percent:"+percent);
      if(percent >= 70){
        //需要上报完成
        this.setData({
         progress:true,
         isUpTime:true
       })
       if(this.data.isUpTime){
        wx.setStorage({
          data: 0,
          key: this.data.videoId,
        })
         this.video_end_progress();
       }
      }
     }
      var surplusTimeTemp = durationTime -currentTime;
      var that = this;
      setTimeout(
        function(){
          var aaa=that.times(surplusTimeTemp)
          that.setData({
            surplusTime:aaa
          })
        },1000)
     
      wx.setStorage({
        data: e.detail.currentTime,
        key: that.data.videoId,
      })
    },
    
    
    //播放结束
    bindended(e){
      //this.videoContext = wx.createVideoContext('myVideo', this);
      //this.videoContext.requestFullScreen();
      // if(this.data.progress==false){
      //   this.progress()
      // }
      if(e.type){
        this.setData({
          historySeconds:0
        })
        

     }
    },
    //视频进入和退出全屏事件
    screenChange(e){

      console.log("参数")
      var fullScreen = e.detail.fullScreen; //值true为进入全屏，false为退出全屏
      console.log(fullScreen)
      if(fullScreen){
        return;
      }
      this.videoContext = wx.createVideoContext('myVideo', this);
      this.videoContext.exitFullScreen(); //退出全屏
      // console.log(JSON.parse(e))
      
      return false;
    
   },
    //更换
    genghuan(e){
      console.log(e)
      this.setData({
        id:e.currentTarget.dataset.item.onlineClassroomId,
        videoId:e.currentTarget.dataset.item.id,
        // detailList:[],
        isplay:true,
        isUpTime:false
      })
      this.init_video_time(e.currentTarget.dataset.item.id)
      this.classdetail()
      // this.viewoList()
      

      //返回顶部
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
    },
  //暂停视频播放
    bindpause(e){
      var that = this;
      console.log(that.data.playLength)
      console.log(that.data.totalLength)
      console.log(Number(that.data.playLength))
      console.log(Number(that.data.totalLength))
      that.setData({
        playLength:Number(that.data.playLength).toFixed(0),
        totalLength:Number(that.data.totalLength).toFixed(0)
      })
      var parse={
        totalSeconds:that.data.playLength,
        videoId:that.data.id
      }
      if(this.data.progress==false){
        that.video_end_progress(parse)
      }
      that.video_end_progress(parse)
    },
 
  //播放
  videoPlay(e){
    // var videoContext = wx.createVideoContext('myvideo', this);
    // this.videoContext.seek(Number(this.data.playLength))
    // this.video()
    this.setData({
      isplay:true,
      // autoplay: true,
    })

  },
  
  // navBar返回
  handlerGobackClick() {
    const pages = getCurrentPages();
    if (pages.length >= 2) {
      wx.navigateBack({
        delta: 1,
        success(res){
    
        }
        
      })
    } else {
      wx.navigateTo({
        url: '/pages/firstpage/firstpage'
      });
    }
    if(this.data.playLength<1){
      this.setData({
        playLength:1
      })
      if(this.data.progress==false){
        this.video_end_progress()
      }
      this.video_end_progress()
      console.log(this.data.playLength)
    }
    
  },
  // 顶部tab切换事件
  toggleCategory(e) {
    console.log(e)
    const that = this;
    that.setData({
      categoryCur: e.detail.index,
      isDoubleClick: e.detail.isDoubleClick,
    });

    if (that.data.isDoubleClick == "1") {
      console.log('添加双击事件')
    }
  },
  //课堂详情
  classdetail(){
    var that=this
    var obj={videoId:that.data.videoId}
    
    classdetails.classroom_detail(obj).then(res=>{
      console.log(res)
      that.setData({
        classobj:res.data.datum,
        detailsId:res.data.datum.id
      })
        wx.getStorage({
        key: 'classContent',
        success (res) {
          console.log(res.data)
          var article = res.data;
          WxParse.wxParse('article', 'html', article, that, 5);
          that.video()
        },
        fail(error){
          console.log(error)
        }
      })
    }).catch(error=>{
      console.log(error)
    })
  },
  //播放视频
  video(){
    var obj={videoId:this.data.detailsId}
    classdetails.watch_video(obj).then(res=>{
      //var runplay=res.data.totalSeconds

      this.setData({
        video:res.data.datum,
        onlineClassroomId:res.data.datum.onlineClassroomId,
        videourl:res.data.datum.videoUrl,
        Url:res.data.datum.videoUrl,
        totalLength:res.data.datum.totalSeconds,
        //playLength:res.data.totalSeconds,
        //timeNumber:Number(runplay),
        //timeNumber:Number(150),
        // autoplay:false,
        videosId:res.data.datum.id
      })
      console.log("外部："+res.data.totalSeconds);
      console.log("内部"+res.data.datum.totalSeconds);
      if(res.data.totalSeconds == res.data.datum.totalSeconds){
        this.setData({
          progress:true
        })
      }else{
        this.setData({
          progress:false
        })
      }



      // var num = Number(this.data.playLength) >= Number(res.data.datum.totalSeconds)
      // this.setData({
      //   num:num
      // })



      // if (Number(this.data.playLength) >= Number(res.data.datum.totalSeconds)){
      //   this.setData({
      //     progress:true,
      //   })
      // }else{
      //   this.setData({
      //     progress: false
      //   })
      // }
     
      
    }).catch(error=>{
      console.log(error)
    })
  },
  // bofangl(){
  //   var that = this
  //   setTimeout(function(){ that.setData({
  //     autoplay:true
  //   }) }, 5000);
  // },
  //课堂详情视频列表
  viewoList(){
    var obj={onlineClassroomId:this.data.id,page:this.data.page}
    classdetails.online_video_list(obj).then(res=>{
      console.log(res)
      var detailList=this.data.detailList
      for(var i=0;i<res.data.datums.length;i++){
        detailList.push(res.data.datums[i])
      }
      this.setData({
        detailList:detailList,
        detailListCount:res.data.count
        // detailList:[]

      })
    }).catch(error=>{
      console.log(error)
    })
  },
  //同步视频进度
  video_end_progress(){
    var obj={videoId:this.data.videosId,totalSeconds:this.data.totalLength}
    console.log("同步视频进度");
    console.log("视频总时长："+this.data.totalLength);
    classdetails.sync_video_progress(obj).then(res=>{
      console.log("同步视频进度返回结果AAAAA");
      console.log(res)
      console.log("同步视频进度返回结果BBBBB");
      if(res.code==0 && res.data.notice!=''){
        wx.showToast({
          title: res.data.notice,
          icon:'none',
          duration:3000
        })
      }
    }).catch(error=>{
      console.log(error)
    })
  },
  
  //分秒转换
  times: function (val) {
                var ss = val%60  
                if(ss<10){
                    ss='0'+ss
                }
                var mm = (val-ss)/60
                if(mm<10){
                    mm='0'+mm
                }
                
              return mm+':'+ss
            },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
        if(this.data.categoryCur==1){
            if(Number(this.data.detailListCount) > Number(this.data.detailList.length)){
                this.setData({
                    page:this.data.page + 1,
                })
                this.viewoList()
            }
        }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})